<template>
	<!--表单详情-->
	<span class="bill-detail-title">单据清单</span>
	<a-divider class="divider-center"/>
	<a-form :model="props.submitFormData" ref="recordForm">

		<a-table
			:dataSource="props.submitFormData.recordList"
			:columns="columns"
			rowKey="id"
			:pagination="false"
			:scroll="{ x: 1500 }">
			<template #bodyCell="{ text, record, index, column }">
				<a-form-item
					v-if="column.dataIndex === 'productId'"
					:rules="[{ required: true, message: '商品编号必填', trigger: 'blur' }]"
					:name="['recordList', index ,'productId']">
					<a-select v-model:value="props.submitFormData.recordList[index].productId" placeholder="商品"
							  @select="fullProductSelect(record, index)"
							  :field-names="{label: 'label',value: 'productId',}"
							  :options="productData" />
				</a-form-item>
				<a-form-item
					v-if="column.dataIndex === 'productName'"
					:rules="[{ required: true, message: '商品全名必填', trigger: 'blur' }]"
					:name="['recordList', index ,'productName']">
					<a-input v-model:value="props.submitFormData.recordList[index].productName" placeholder="商品" />
				</a-form-item>
				<a-form-item
					v-if="column.dataIndex === 'productType'"
					:rules="[{ required: true, message: '商品类型', trigger: 'blur' }]"
					:name="['recordList', index ,'productType']">
					<a-input v-model:value="props.submitFormData.recordList[index].productType" placeholder="商品" />
				</a-form-item>
				<a-form-item
					v-if="column.dataIndex === 'measureUnit'"
					:rules="[{ required: true, message: '单位必填', trigger: 'blur' }]"
					:name="['recordList', index ,'measureUnit']">
					<a-input v-model:value="props.submitFormData.recordList[index].measureUnit" placeholder="单位"  />
				</a-form-item>
				<a-form-item
					v-if="column.dataIndex === 'productSpecifications'"
					:rules="[{ required: true, message: '规格必填', trigger: 'blur' }]"
					:name="['recordList', index ,'productSpecifications']">
					<a-input v-model:value="props.submitFormData.recordList[index].productSpecifications" placeholder="商品规格" />
				</a-form-item>
				<a-form-item
					v-if="column.dataIndex === 'retrievalId' "
					:rules="[{ required: true, message: '出库仓库', trigger: 'blur' }]"
					:name="['recordList', index ,'retrievalId']">
					<a-select v-model:value="props.submitFormData.recordList[index].retrievalId" @select="fullPrice(record, index, 'price')" placeholder="出库仓库">
						<a-select-option v-for="item in wareData" :value="item.warehouse.wareId">{{item.warehouse.wareName}}</a-select-option>
					</a-select>
				</a-form-item>
				<a-form-item
					v-if="column.dataIndex === 'texRate'"
					:rules="[{ required: true, message: '税率必填', trigger: 'blur' }]"
					:name="['recordList', index ,'texRate']">
					<a-select  v-model:value="props.submitFormData.recordList[index].texRate" :options="texRateOptions" @select="fullPrice(record, index)" placeholder="请选择税率"></a-select>
				</a-form-item>
				<a-form-item
					v-if="column.dataIndex === 'planQuantity'"
					:rules="[{ required: true, message: '出库数量必填', trigger: 'blur' }, { validator: (rule, value) => validateGreaterThanZero(rule, value, record, index, 'price'), trigger: 'blur' }]"
					:name="['recordList', index ,'planQuantity']">
					<a-input-number v-model:value="props.submitFormData.recordList[index].planQuantity" @change="fullPrice(record, index, 'price')" placeholder="出库数量" />
				</a-form-item>
				<a-form-item
					v-if="column.dataIndex === 'univalence'"
					:rules="[{ required: true, message: '含税单价必填', trigger: 'blur' }]"
					:name="['recordList', index ,'univalence']">
					<a-input-number v-model:value="props.submitFormData.recordList[index].univalence" @change="fullPrice(record, index)" placeholder="含税单价" />
				</a-form-item>
				<a-form-item :name="['recordList', index ,'discount']"
							 :rules="[{ required: true, message: '打折必填', trigger: 'blur' }]"
							 v-if="column.dataIndex === 'discount'">
					<a-input-number v-model:value="record.discount" placeholder="打折%" />
				</a-form-item>
				<a-form-item v-if="column.dataIndex === 'money'"
							 :rules="[{ required: true, message: '含税金额必填', trigger: 'blur' }]"
							 :name="['recordList', index ,'money']" >
					<a-input-number v-model:value="record.money" placeholder="含税金额" />
				</a-form-item>

				<a-form-item v-if="column.dataIndex === 'texMoney'"
							 :name="['recordList', index ,'texMoney']" >
					<a-input-number v-model:value="record.texMoney" placeholder="税额" />
				</a-form-item>
				<a-form-item :name="['recordList', index ,'cost']" v-if="column.dataIndex === 'cost'">
					<a-input-number v-model:value="record.cost" placeholder="成本" />
				</a-form-item>

				<a-form-item :name="['recordList', index ,'remarks']" v-if="column.dataIndex === 'remarks'">
					<a-input v-model:value="record.remarks" placeholder="备注" />
				</a-form-item>

				<a-button v-if="column.dataIndex === 'action'" @click="deleteRow(index)" danger>
					删除
				</a-button>
			</template>

			<template #summary>
				<a-table-summary-row>
					<a-table-summary-cell>合计</a-table-summary-cell>
					<a-table-summary-cell :colSpan="3">
						<a-typography-text ></a-typography-text>
					</a-table-summary-cell>
					<a-table-summary-cell>
						<a-typography-text >{{totalMoney.totalCount}}</a-typography-text>
					</a-table-summary-cell>
					<a-table-summary-cell>
						<a-typography-text ></a-typography-text>
					</a-table-summary-cell>
					<a-table-summary-cell >
						<a-typography-text ></a-typography-text>
					</a-table-summary-cell>
					<a-table-summary-cell>
						<a-typography-text ></a-typography-text>
					</a-table-summary-cell>
					<a-table-summary-cell >
						<a-typography-text >{{totalMoney.totalPrice}}</a-typography-text>
					</a-table-summary-cell>
					<a-table-summary-cell >
						<a-typography-text >{{totalMoney.totalTaxAmount}}</a-typography-text>
					</a-table-summary-cell>
				</a-table-summary-row>
			</template>
		</a-table>
	</a-form>

	<!--	操作		-->
	<div class="modal-text-button-group">
		<span >
			<SelectOutlined class="modal-header-icon"/>
			<a class="modal-text-button" @click="billForm.onOpen">选择历史单据</a>
		</span>
		<span style="margin-left: 50px">
			<PlusOutlined class="modal-header-icon"/>
			<a @click="addRow" class="modal-text-button">添加商品</a>
		</span>
	</div>
	<div style="margin-top: 60px"></div>

	<ImsBillSelector ref="billForm" type="order" @successful="billSelectorSuc"></ImsBillSelector>


</template>

<script setup>
import {ref} from "vue";
import imsProductApi from "@/api/ims/imsProductApi";
import tool from "@/utils/tool";
import ImsBillSelector from "@/components/Ims/BillSelector/index.vue";
import imsOrderApi from "@/api/ims/imsOrderApi";
import {message} from "ant-design-vue";
import imsInventoryApi from "@/api/ims/imsInventoryApi";
import imsBillApi from "@/api/ims/imsBillApi";

const props = defineProps({
	submitFormData: {
		type: Object,
		default: () => ({
			header: {
				userIds: [{}],
				invoiceType: '不开票',
			},
			recordList: [],
		}),
	},
	type: {
		type: String,
		default: () => ''
	},
	typeName: {
		type: String,
		default: () => ''
	},
});

const productData = ref([])
const totalMoney = ref({
	totalCount: '',
	totalPrice: '',
	totalTaxAmount: ''
})
const texRateOptions = ref([])
const recordForm = ref(null);
const wareData = ref([])

// 动态表字段
const columns = [
	{
		title: () => {
			return h('span', [
				h('span', { style: { color: 'red', marginRight: '4px' } }, '*'),
				'商品全名'
			]);
		},
		dataIndex: 'productId',
		key: 'productId',
		width: 200,
		fixed: 'left',
	},
	{
		title: () => {
			return h('span', [
				h('span', { style: { color: 'red', marginRight: '4px' } }, '*'),
				'商品规格'
			]);
		},
		dataIndex: 'productSpecifications',
		key: 'productSpecifications',
		width: 120,
	},
	{
		title: () => {
			return h('span', [
				h('span', { style: { color: 'red', marginRight: '4px' } }, '*'),
				'单位'
			]);
		},
		dataIndex: 'measureUnit',
		key: 'measureUnit',
		width: 120
	},


	{
		title: () => {
			return h('span', [
				h('span', { style: { color: 'red', marginRight: '4px' } }, '*'),
				'出库数量'
			]);
		},
		dataIndex: 'planQuantity',
		key: 'planQuantity',
		width: 120
	},
	{
		title: () => {
			return h('span', [
				h('span', { style: { color: 'red', marginRight: '4px' } }, '*'),
				'税率'
			]);
		},
		dataIndex: 'texRate',
		key: 'texRate',
		width: 120
	},
	{
		title: () => {
			return h('span', [
				h('span', { style: { color: 'red', marginRight: '4px' } }, '*'),
				'含税单价'
			]);
		},
		dataIndex: 'univalence',
		key: 'univalence',
		width: 120
	},
	{

		title: () => {
			return h('span', [
				h('span', { style: { color: 'red', marginRight: '4px' } }, '*'),
				'打折%'
			]);
		},
		dataIndex: 'discount',
		key: 'discount',
		width: 120
	},
	{
		title: () => {
			return h('span', [
				h('span', { style: { color: 'red', marginRight: '4px' } }, '*'),
				'含税金额'
			]);
		},
		dataIndex: 'money',
		key: 'money',
		width: 120
	},
	{
		title: '税额',
		dataIndex: 'texMoney',
		key: 'texMoney',
		width: 120
	},
	{
		title: '成本',
		dataIndex: 'cost',
		key: 'cost',
		width: 120
	},
	{
		title: '备注',
		dataIndex: 'remarks',
		key: 'remarks',
		width: 300
	},

	{
		title: '操作',
		dataIndex: 'action',
		key: 'action',
		width: 100,
		fixed: 'right',
	},
];




const billForm = ref()


const billSelectorSuc = (val) => {
	console.log('选择的单据头', val)
	if (val?.byOrder) {
		// 回显
		imsOrderApi.imsBillDetail({billId: val.billId}).then(res => {
			dataFull(res);
		})
	} else {
		// 回显
		imsBillApi.imsBillDetail({billId: val.billId}).then(res => {
			dataFull(res)

		})
	}
}
function dataFull(res) {
	console.log('回显数据：', res)
	props.submitFormData.header = res.header
	props.submitFormData.recordList = res.recordList
	totalMoney.value.totalCount = props.submitFormData.header.orderNum
	totalMoney.value.totalPrice = props.submitFormData.header.orderAmount

	// 出库清空供应商字段，入库清空客户字段
	if (props.submitFormData.header.billType.includes('出库')) {
		props.submitFormData.header.supplierIds = null
	} else {
		props.submitFormData.header.customerIds = null
	}
	// 默认字段清空
	props.submitFormData.header.billStatus = null
	props.submitFormData.header.createTime = null

	props.submitFormData.recordList.forEach((record, index) => {
		fullProductSelect(record, index)
	})
	// 生成单据编号
	imsOrderApi.getBillNo(props.typeName).then(res => {
		props.submitFormData.header.billOrderNo = res
		console.log('获取的单据编号：', res )
	})

}


const emit = defineEmits({ successful: null })

onMounted(() => {
	// 获取商品
	imsProductApi.imsProductPage({
		current: 1,
		size: 9999
	}).then(res => {
		// 商品名称 = 商品编号+商品名称
		res.records.map(item => {
			item.label = item.productCode +'-'+ item.productName
		})
		productData.value = res.records
	})

	// // 获取单位
	// texRateOptions.value = tool.dictList('unit')

	// 获取税率，默认选中无税率
	texRateOptions.value = tool.dictList('tax_rate')

	// TODO 仅出库入库操作库存
	console.log('库存判断：', props.type === 'bill')
	if (props.type === 'bill') {
		columns.splice(3, 0, { // 在索引 1 处插入
			title: () => {
				return h('span', [
					h('span', { style: { color: 'red', marginRight: '4px' } }, '*'),
					'出库仓库'
				]);
			},
			index: 1,
			dataIndex: 'retrievalId',
			key: 'retrievalId',
			width: 150,
		});
	}
})

// 校验
const validate = () => {
	return recordForm.value.validate();
};

// 添加一行
const addRow = () => {
	props.submitFormData.recordList.push({
		id: Date.now(),
		discount: 100,
		texRate: 0,
		planQuantity: 1
	});
	fullPrice()
};

// 删除一行
const deleteRow = (index) => {
	props.submitFormData.recordList.splice(index, 1);
	fullPrice()
};

// 计算总金额，税额以及总税额，含税金额以及含税总金额，
const fullPrice = (record, index, priceFlag) => {
	// 计算每一条
	if (record) {
		// 确保 submitFormData 和 recordList 已定义
		if (props.submitFormData && props.submitFormData.recordList && props.submitFormData.recordList[index]) {
			// 计算税额
			if (record.univalence && record.planQuantity && record.texRate) {
				props.submitFormData.recordList[index].texMoney =
					Number(record.planQuantity) * Number(record.univalence) * Number(record.texRate) / 100;
				console.log('计算税额：', props.submitFormData.recordList[index]);
			}
			// 计算含税金额
			if (record.planQuantity && record.univalence) {
				props.submitFormData.recordList[index].money = Number(record.planQuantity) * Number(record.univalence);
			}
		} else {
			console.error('submitFormData或recordList未定义');
		}
	}


	// 计算合计
	let count = 0;
	let price = 0;
	let tex = 0;
	props.submitFormData.recordList.forEach(item => {
		if (item.planQuantity) {
			count += item.planQuantity;
		}
		if (item.planQuantity && item.univalence) {
			price += Number(item.planQuantity.toString()) * Number(item.univalence.toString())
		}
		// 计算税额
		if (item.texRate && item.planQuantity && item.univalence) {
			tex += Number(item.planQuantity.toString()) * Number(item.univalence.toString()) * Number(item.texRate.toString()) / 100
			tex = Number(tex.toFixed(2))
		}
	})
	totalMoney.value = {
		totalCount: count,
		totalPrice: price,
		totalTaxAmount: tex
	}
	props.submitFormData.header.orderAmount = price;
	props.submitFormData.header.orderNum = count;


	// TODO 仅出库入库操作库存
	if (props.type !== 'bill') {
		return
	}
	if (priceFlag) {
		wareData.value.map(item => {
			console.log(item.productId, record.productId)
			if (item.productId === record.productId) {

				// 获取库存
				console.log('库存情况：', item)
				let stock = Number(item.count)
				// 获取出库数量
				let planQuantity = Number(record.planQuantity)
				// 判断库存是否小于出库数量
				if (stock < planQuantity) {
					// 提示库存不足
					message.error('当前仓库商品库存仅剩'+ stock +'件，无法出库该数量！')
					// 清空数据
					// submitFormData.value.recordList[index].planQuantity = 1
				} else {
					// 库存充足，填充成本
					props.submitFormData.recordList[index].cost = item.cost
					console.log('填充成本：', props.submitFormData)
				}
			}
		})
		console.log('处理库存范围校验：', record)
	}


}

/**
 * 选择商品回显规格和单位
 */
const fullProductSelect = (val, index) => {


	productData.value.map(item => {
		if (item.productId === val.productId) {
			props.submitFormData.recordList[index].productSpecifications = item.productSpecifications;
			props.submitFormData.recordList[index].measureUnit = item.measureUnit;
			props.submitFormData.recordList[index].univalence = item.univalence;
			props.submitFormData.recordList[index].cost = item.costPrice;

		}
	});
	fullPrice(val, index, 'price')

	// TODO 仅出库入库操作库存
	if (props.type !== 'bill') {
		return
	}
	// 获取库存以及仓库
	imsInventoryApi.detail({productId: val.productId}).then(res => {
		wareData.value = res
		console.log('获取库存详情：', res)
	})
}



// 库存校验
const validateGreaterThanZero = (rule, value, record, index, falg) => {
	// TODO 仅出库入库操作库存
	if (props.type !== 'bill') {
		return new Promise((resolve, reject) => {
			resolve()
		});
	}

	console.log('校验逻辑：', rule, value, record, index, falg)
	// 必选大于0，必选输入仓库，库存数量充足
	return new Promise((resolve, reject) => {
		if (record.planQuantity <= 0) {
			reject(new Error('数量必须大于0'));
		} else if (!record.retrievalId){
			reject(new Error('库存不足'));
		} else {
			let falgRes = true
			wareData.value.map(item => {
				if (item.productId === record.productId) {
					console.log('库存情况：', item)
					let stock = Number(item.count)
					let planQuantity = Number(record.planQuantity)
					if (stock < planQuantity) {
						reject(new Error('库存不足'));
						falgRes = false
					}
				}
			})
			if (falgRes) {
				resolve();
			}

		}
	});

}

// 暴露 validate 方法
defineExpose({ validate });
</script>
